package com.firefly.app.cordova.plugins;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;

import com.firefly.app.biz.yhc.dto.ResponseDTO;
import com.xiaomi.market.sdk.UpdateResponse;
import com.xiaomi.market.sdk.UpdateStatus;
import com.xiaomi.market.sdk.XiaomiUpdateAgent;
import com.xiaomi.market.sdk.XiaomiUpdateListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

public class HomePlugin  extends CordovaPlugin implements CordovaInterface{
		private final ExecutorService threadPool = Executors.newCachedThreadPool(); 
		
		
	
	    /** 
	     * 注意 构造方法不能为 
	     *  
	     * HomePlugin(){}   
	     * 可以不写或者 定义为如下 
	     *   
	     */  
	    public HomePlugin() {

	    }  
	  
	    CallbackContext callbackContext;  
	   
	    @Override  
	    public boolean execute(final String action,final  org.json.JSONArray args,final CallbackContext callbackContext) throws org.json.JSONException {  
	    	
	    	cordova.getThreadPool().execute(new Runnable() {
	            public void run() {
	                try {
						execPlugin(action, args, callbackContext);
					} catch (Exception e) {
						e.printStackTrace();
						Log.e("packPlugin", "插件调用出错");
						callbackContext.error("插件调用出错");
					}
	            }
	        });
	        
	        return true;  
	    }
	    

	    private void execPlugin(String action, org.json.JSONArray args,CallbackContext callbackContext) throws org.json.JSONException {
		    	this.callbackContext = callbackContext;  
		    	Log.e("callbackContext", action);  
		    	if (action.equals("getCurrVersion")) {
		    		ResponseDTO responseDTO = new ResponseDTO();
		    		responseDTO.setBody(getAppVersionName(getActivity()));
		    		callbackContext.success(com.alibaba.fastjson.JSONObject.toJSONString(responseDTO)); 
				}
		    	
		    	if (action.equals("checkVersion")) {
		    		XiaomiUpdateAgent.setUpdateListener(new XiaomiUpdateListener() {

		                @Override
		                public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
		                    switch (updateStatus) {
		                        case UpdateStatus.STATUS_UPDATE:
		                             // 有更新， UpdateResponse为本次更新的详细信息
		                             // 其中包含更新信息，下载地址，MD5校验信息等，可自行处理下载安装
		                             // 如果希望 SDK继续接管下载安装事宜，可调用
		                        	alarmUpdate(updateInfo);
		                             break;
		                         case UpdateStatus.STATUS_NO_UPDATE:
		                        	 new AlertDialog.Builder(getActivity()).setTitle("")//设置对话框标题  
		                 	        .setMessage("当前已是最新版本").show();//设置显示的内容  
		                            break;
		                        case UpdateStatus.STATUS_NO_WIFI:
		                            // 设置了只在WiFi下更新，且WiFi不可用时， UpdateResponse为null
		                            break;
		                        case UpdateStatus.STATUS_NO_NET:
		                            // 没有网络， UpdateResponse为null
		                        	 new AlertDialog.Builder(getActivity()).setTitle("")//设置对话框标题  
			                 	        .setMessage("当前网络不通，请检查您的网络").show();//设置显示的内容  
		                            break;
		                        case UpdateStatus.STATUS_FAILED:
		                            // 检查更新与服务器通讯失败，可稍后再试， UpdateResponse为null
		                            break;
		                        case UpdateStatus.STATUS_LOCAL_APP_FAILED:
		                            // 检查更新获取本地安装应用信息失败， UpdateResponse为null
		                            break;
		                        default:
		                            break;
		                    }
		                }
		            });
		            XiaomiUpdateAgent.update(getActivity());
				}
		    	
		        if (action.equals("toBack")) {  
		        	 Intent intent = new Intent(Intent.ACTION_MAIN);      
		             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);      
		             intent.addCategory(Intent.CATEGORY_HOME);      
		             getActivity().startActivity(intent);  
		          
		        }
	    }
	    
	    private void alarmUpdate(UpdateResponse updateInfo){
	        new AlertDialog.Builder(getActivity()).setTitle("有新版本了，赶快更新看看吧")//设置对话框标题  
	        .setMessage(""+updateInfo.updateLog)//设置显示的内容  
	        .setPositiveButton("立即升级",new DialogInterface.OnClickListener() {//添加确定按钮  
	            @Override  
	            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件  
	                XiaomiUpdateAgent.arrange();
	            }
	        }).setNegativeButton("稍后再说",new DialogInterface.OnClickListener() {//添加返回按钮  
	            @Override  
	            public void onClick(DialogInterface dialog, int which) {//响应事件  
	                Log.i("alertdialog"," 不更新，稍后再说！");  
	            }
	        }).show();//在按键响应事件中显示此对话框  
	    }
	    
	    /** 
	     * 返回当前程序版本名 
	     */  
	    public static String getAppVersionName(Context context) {  
	        String versionName = "";  
	        try {  
	            // ---get the package info---  
	            PackageManager pm = context.getPackageManager();  
	            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);  
	            versionName = pi.versionName;  
//	            versioncode = pi.versionCode;
	            if (versionName == null || versionName.length() <= 0) {  
	                return "";  
	            }  
	        } catch (Exception e) {  
	            Log.e("VersionInfo", "Exception", e);  
	        }  
	        return versionName;  
	    }  
	    
	    
	    @Override
		public ExecutorService getThreadPool() {
			return threadPool;
		}




		@Override
		public void startActivityForResult(CordovaPlugin command,
				Intent intent, int requestCode) {
			// TODO Auto-generated method stub
			
		}




		@Override
		public void setActivityResultCallback(CordovaPlugin plugin) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public Activity getActivity() {
			return this.cordova.getActivity();
		}
	    
	  
}
